package thu.cs.segroup.test;

import jade.core.Agent;
import jade.core.AID;
import jade.domain.FIPAAgentManagement.*;
import jade.domain.DFService;
import jade.domain.FIPANames;
import jade.lang.acl.ACLMessage;

import java.util.*;
import java.io.*;

import thu.cs.segroup.entity.TestTask;

public class Writer extends Agent {


	protected void setup() {

		/** Search with the DF for the name of the ObjectReaderAgent **/
		AID reader = new AID();
		DFAgentDescription dfd = new DFAgentDescription();  
		ServiceDescription sd = new ServiceDescription();
		sd.setType("ObjectReaderAgent"); 
		dfd.addServices(sd);
		try {
			while (true) {
				System.out.println(getLocalName()+ " waiting for an ObjectReaderAgent registering with the DF");
				SearchConstraints c = new SearchConstraints();
				c.setMaxDepth(new Long(3));
				DFAgentDescription[] result = DFService.search(this,dfd,c);
				if ((result != null) && (result.length > 0)) {
					dfd = result[0]; 
					reader = dfd.getName();
					break;
				}
				Thread.sleep(10000);
			}
		} catch (Exception fe) {
			fe.printStackTrace();
			System.err.println(getLocalName()+" search with DF is not succeeded because of " + fe.getMessage());
			doDelete();
		}

		System.out.println(getLocalName()+" agent sends ACLMessages whose content is a Java object");

		try {
			ACLMessage msg = new ACLMessage(ACLMessage.INFORM);

			msg.addReceiver(reader);

			// TestCase p = new TestCase("TestTest", 1, 1);
			TestTask p = new TestTask();
			msg.setContentObject(p);
			msg.setLanguage("JavaSerialization");
			send(msg);
			System.out.println(getLocalName()+" sent 1st msg "+msg);

			/*msg.setDefaultEnvelope();
			msg.getEnvelope().setAclRepresentation(FIPANames.ACLCodec.BITEFFICIENT);
			send(msg);
			System.out.println(getLocalName()+" sent 1st msg with bit-efficient aclCodec "+msg);

			msg.getEnvelope().setAclRepresentation(FIPANames.ACLCodec.XML); 
			send(msg);
			System.out.println(getLocalName()+" sent 1st msg with xml aclCodec "+msg);

			p = new TestCase("TestTestTest", 1, 1);
			msg.setContent(p.toString());
			msg.setLanguage("StringLanguage");
			msg.setDefaultEnvelope(); //reset the envelope to default ACLCodec
			send(msg);
			System.out.println(getLocalName()+" sent 2nd msg "+msg);

			msg.getEnvelope().setAclRepresentation(FIPANames.ACLCodec.BITEFFICIENT); 
			send(msg);
			System.out.println(getLocalName()+" sent 2nd msg with bit-efficient aclCodec "+msg);

			msg.getEnvelope().setAclRepresentation(FIPANames.ACLCodec.XML); 
			send(msg);
			System.out.println(getLocalName()+" sent 2nd msg with xml aclCodec "+msg);*/
		} catch (IOException e ) {
			e.printStackTrace();
		}
		doDelete(); // kill itself because it has completed its task.
	}

}
